package stark.app.function.applock;

import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.applock.lib.AppLockBean;
import com.stark.applock.lib.AppLockModule;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.app.R;
import stark.app.databinding.ActivityAppLockAppsBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.utils.RxUtil;

/**
 * Author：daizhongbin on 2022/8/4
 * Email：1027154338@qq.com
 * Desc:
 */
public class AppLockAppsActivity extends BaseNoModelActivity<ActivityAppLockAppsBinding> {

    private AppAdapter mAppAdapter;

    @Override
    protected int onCreate() {
        return R.layout.activity_app_lock_apps;
    }

    @Override
    protected void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mDataBinding.rvApps.setLayoutManager(layoutManager);
        AppAdapter appAdapter = new AppAdapter();
        mAppAdapter = appAdapter;
        appAdapter.setOnItemClickListener(this);
        mDataBinding.rvApps.setAdapter(appAdapter);
    }

    @Override
    protected void initData() {
        loadAppData();
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        AppLockBean bean = mAppAdapter.getItem(position);
        if (bean.isLocked) {
            AppLockModule.unlockApp(bean.pckName);
            bean.isLocked = false;
        } else {
            AppLockModule.lockApp(bean.pckName);
            bean.isLocked = true;
        }
        adapter.notifyItemChanged(position);
    }

    private void loadAppData() {
        showDialog("加载数据中...");
        RxUtil.create(new RxUtil.Callback<List<AppLockBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<AppLockBean>> emitter) {
                emitter.onNext(AppLockModule.getApps());
            }

            @Override
            public void accept(List<AppLockBean> beans) {
                dismissDialog();
                mAppAdapter.setNewInstance(beans);
            }
        });
    }
}
